package com.yimi.yinhepda.db.mapper;

import android.util.Log;

import com.j256.ormlite.dao.RawRowMapper;

import java.lang.reflect.Field;
import java.sql.SQLException;

/**
 * Created by user on 2016/11/15.
 */
public class MyRawMapper<T> implements RawRowMapper {
    private Class clazz;
    public MyRawMapper(Class<T> clazz){
        Log.i("MyRawMapper","MyRawMapper");
        this.clazz = clazz;
    }

    @Override
    public T mapRow(String[] columnNames, String[] resultColumns) throws SQLException {
        try{
            Object obj = clazz.newInstance();
                for(int i =0;columnNames!=null&&i<columnNames.length;i++){
                    Field field = null;
                    try{
                        field = clazz.getDeclaredField(columnNames[i]);
                    }catch (Exception ex){
                    }
                    Log.i("jin",columnNames[i]);
                    if(field!=null){
                        field.setAccessible(true); //使用反射机制可以打破封装性，导致了java对象的属性不安全。
                        String type = field.getGenericType().toString();
                        Log.i("jintype",type);
                        if(type.equals("class java.lang.Integer")){
                            if(resultColumns[i]==null){
                                field.set(obj,0);
                            }else{
                                field.set(obj, Integer.parseInt(resultColumns[i]));
                            }

                        }else if(type.equals("class java.lang.Double")){
                            if(resultColumns[i]==null){
                                field.set(obj,0);
                            }else{
                                field.set(obj, Double.parseDouble(resultColumns[i]));
                            }

                        }else if(type.equals("class java.lang.String")){

                            field.set(obj,resultColumns[i]);
                        }else if(type.equals("int")){
                            if(resultColumns[i]==null){
                                field.set(obj,0);
                            }else{
                                field.set(obj, Integer.parseInt(resultColumns[i]));
                            }

                        }else if(type.equals("double")){
                            if(resultColumns[i]==null){
                                field.set(obj,0);
                            }else{
                                field.set(obj, Double.parseDouble(resultColumns[i]));
                            }
                        }
                    }

                }
            Log.i("jin1",obj.toString());
            return (T)obj;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
